package com.lsh.ofc.proxy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.proxy.model.Goods;
import com.lsh.ofc.proxy.util.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 商品服务代理
 *
 * @author huangdong
 * @date 16/8/28
 */
@Service
@Slf4j
public class GoodsServiceProxy {

    @Value("${goods.server.path}")
    private String goodsServerPath;

    @Value("${base.goods.server.path}")
    private String baseGoodsServerPath;

    private static final String GET_BY_GOODS_ITEM_URI = "/v1/Market/Item/getListBySkuIds";

    private Header[] buildHeaders(Long venderId) {

        Header[] headers = {new BasicHeader("api-version", "1.1"),
                new BasicHeader("platform", "ofc"),
                new BasicHeader("venderId", venderId + ""),
                new BasicHeader("sign", "md5")};

        log.info("goods header is " + JSON.toJSONString(headers));
        return headers;
    }

    /**
     * 根据商品码集合获取商品信息集合
     *
     * @param goodsCodes
     * @return
     * @throws BusinessException
     */
    public Map<Long, Goods> getGoodsInfoMapByGoodsCodesItem(Collection<Long> goodsCodes, Long venderId) throws BusinessException {
        String uri = this.baseGoodsServerPath + GET_BY_GOODS_ITEM_URI;

        if (CollectionUtils.isEmpty(goodsCodes)) {
            return Collections.emptyMap();
        }
        List<Long> skuIds = new ArrayList<>();
        for (Long goodsCode : goodsCodes) {
            skuIds.add(goodsCode);
        }
        List<BasicNameValuePair> pairs = new ArrayList<>(2);
        pairs.add(new BasicNameValuePair("sku_id", skuIds.toString()));
        pairs.add(new BasicNameValuePair("venderId", venderId + ""));
        log.info("uri = " + uri + " pairs is " + JSON.toJSONString(pairs));
        HttpEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
        String result = HttpClientUtils.post(uri, entity, this.buildHeaders(venderId)).getData();
        JSONArray contentArray = JSON.parseObject(result).getJSONArray("content");
        if (contentArray == null || contentArray.isEmpty()) {
            log.error("商品信息不存在！goodsCodes=" + goodsCodes);
            return Collections.emptyMap();
        }

        Map<Long, JSONObject> contentMap = new HashMap<>();
        for (int i = 0; i < contentArray.size(); i++) {
            JSONObject content = contentArray.getJSONObject(i);

            JSONObject skuInfo = content.getJSONObject("sku_info");
            if (skuInfo == null) {
                continue;
            }
            Long goodscode = skuInfo.getLong("sku_id");

            contentMap.put(goodscode, content);
        }

        Map<Long, Goods> map = new HashMap<>();
        for (Long goodsCode : goodsCodes) {
            JSONObject content = contentMap.get(goodsCode);
            if (content == null) {
                log.error("商品信息不存在！content goodsCode=" + goodsCode);
                continue;
            }

            JSONObject goodsInfo = content.getJSONObject("goods_info");
            JSONObject itemInfo = content.getJSONObject("item_info");

            if(goodsInfo == null){
                log.error("商品信息不存在 goodsInfo ！goodsCode=" + goodsCode);
                continue;
            }

            if(itemInfo == null){
                log.error("商品信息不存在 itemInfo ！goodsCode=" + goodsCode);
                continue;
            }

            Goods goods = new Goods();
            goods.setGoodsCode(goodsCode);
            goods.setSkuCode(goodsInfo.getLong("item_id"));
            goods.setSkuDefine(itemInfo.getInteger("sku_define"));
            goods.setSupplySkuCode(goodsInfo.getString("goods_id"));

            goods.setPurchaseUnit(goodsInfo.getString("purchase_unit"));
            goods.setPurchaseUnitNu(goodsInfo.getString("purchase_unit_nu"));

            map.put(goodsCode, goods);
        }

        return map;
    }
}
